//package com.alibaba.cirtus.ots.application.adapter.ability.facade.service.dp.mndataif002;
//
//import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerAddressSDO;
//import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerSDO;
//import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerSaleScopeSDO;
//import com.alibaba.citrus.ots.common.exception.FacadeException;
//import com.alibaba.cz.base.tool.log.Log;
//import com.alibaba.cz.base.tool.message.ErrorMessage;
//import com.alibaba.lattice2.epoch.sdk.model.Result;
//import com.epoch.app.otsplatformenhance.domain.customer.dto.BatchQueryRequest;
//import com.epoch.app.otsplatformenhance.domain.customer.dto.BatchQueryResponse;
//import com.epoch.app.otsplatformenhance.domain.customer.dto.*;
//import com.epoch.app.otsplatformenhance.domain.customer.model.Customer;
//import com.epoch.app.otsplatformenhance.domain.customer.service.CustomerService;
//import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.*;
//import com.epoch.app.otsplatformenhance.domain.customeraddress.model.CustomerAddress;
//import com.epoch.app.otsplatformenhance.domain.customeraddress.service.CustomerAddressService;
//import com.epoch.app.otsplatformenhance.domain.customersalescope.dto.*;
//import com.epoch.app.otsplatformenhance.domain.customersalescope.model.CustomerSaleScope;
//import com.epoch.app.otsplatformenhance.domain.customersalescope.service.CustomerSaleScopeService;
//import com.google.common.collect.Lists;
//import org.apache.commons.collections4.CollectionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.BeanUtils;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//import java.util.*;
//import java.util.stream.Collectors;
//import java.util.stream.IntStream;
//
///**
// * @author wangyibing
// */
//@Component
//public class MnDataIf002SyncUtils {
//    Log log = Log.getLogger(MnDataIf002SyncUtils.class);
//    private static final int LIMIT = 1000;
//    @Resource
//    private CustomerService customerService;
//
//    @Resource
//    private CustomerSaleScopeService customerSaleScopeService;
//
//    @Resource
//    private CustomerAddressService customerAddressService;
//
//    public boolean saveOrUpdateCustomerMainData(CustomerSDO customerSDO) {
//        // 3、根据客户编码查询平台的数据，存在就更新 不存在就新增
//        LoadCustomerRequest loadCustomerRequest = new LoadCustomerRequest();
//        loadCustomerRequest.setCode(customerSDO.getCode());
//        Customer customer = customerService.loadCustomer(loadCustomerRequest);
//        if (customer != null && customer.getId() != null) {
//            Customer updateRequest = new Customer();
//            BeanUtils.copyProperties(customerSDO, updateRequest);
//            updateRequest.setId(customer.getId());
//            updateRequest.setGmtModified(new Date());
//            updateRequest.setFeatures(customerSDO.getFeatures());
//            UpdateCustomerResponse updateCustomerResponse = customerService.updateCustomer(updateRequest);
//            return updateCustomerResponse.getCount() == 1;
//        } else {
//            Customer createRequest = new Customer();
//            BeanUtils.copyProperties(customerSDO, createRequest);
//            createRequest.setGmtCreate(new Date());
//            createRequest.setGmtModified(new Date());
//            createRequest.setFeatures(customerSDO.getFeatures());
//            CreateCustomerResponse customerResponse = customerService.createCustomer(createRequest);
//            return StringUtils.isNotEmpty(customerResponse.getLastInsertId());
//        }
//    }
//
//    public boolean saveOrUpdateCustomerSaleScope(CustomerSaleScopeSDO customerSaleScopeSDO) {
//        CustomerSaleScopeLoadListRequest customerSaleScopeLoadListRequest = new CustomerSaleScopeLoadListRequest();
//        customerSaleScopeLoadListRequest.setCustomerCode(customerSaleScopeSDO.getCustomerCode());
//        customerSaleScopeLoadListRequest.setChannelCode(customerSaleScopeSDO.getChannelCode());
//        customerSaleScopeLoadListRequest.setItemGroup(customerSaleScopeSDO.getItemGroup());
//        customerSaleScopeLoadListRequest.setOrgSaleOrganizationCode(customerSaleScopeSDO.getOrgSaleOrganizationCode());
////        customerSaleScopeLoadListRequest.setOrgSaleChannelCode(customerSaleScopeSDO.getOrgSaleChannelCode());
////        customerSaleScopeLoadListRequest.setOrgSaleDepartmentCode(customerSaleScopeSDO.getOrgSaleDepartmentCode());
//        Result<List<CustomerSaleScope>> listResult = customerSaleScopeService.loadCustomerSaleScopeList(customerSaleScopeLoadListRequest);
//        if (CollectionUtils.isNotEmpty(listResult.getResult())) {
//            CustomerSaleScope origin = listResult.getResult().stream().findFirst().get();
//            CustomerSaleScope customerSaleScope = new CustomerSaleScope();
//            BeanUtils.copyProperties(customerSaleScopeSDO, customerSaleScope);
//            customerSaleScope.setId(origin.getId());
//            customerSaleScope.setGmtModified(new Date());
//            customerSaleScope.setPrincipal(null);
//            customerSaleScope.setFeatures(customerSaleScopeSDO.getFeatures());
//            UpdateCustomerSaleScopeResponse updateCustomerSaleScopeResponse = customerSaleScopeService.updateCustomerSaleScope(customerSaleScope);
//            return updateCustomerSaleScopeResponse.getCount() == 1;
//        } else {
//            CustomerSaleScope customerSaleScope = new CustomerSaleScope();
//            BeanUtils.copyProperties(customerSaleScopeSDO, customerSaleScope);
//            customerSaleScope.setGmtModified(new Date());
//            customerSaleScope.setGmtCreate(new Date());
//            customerSaleScope.setFeatures(customerSaleScopeSDO.getFeatures());
//            CreateCustomerSaleScopeResponse scopeResponse = customerSaleScopeService.createCustomerSaleScope(customerSaleScope);
//            return StringUtils.isNotEmpty(scopeResponse.getLastInsertId());
//        }
//    }
//
//    public boolean saveOrUpdateCustomerAddress(CustomerAddressSDO customerAddressSDO) {
//
//        //先根据customerCode查询是否有客户主数据，没有就直接return
//        if (StringUtils.isBlank(customerAddressSDO.getCustomerCode()) ||
//                StringUtils.isBlank(customerAddressSDO.getAddressCode()) ||
//                StringUtils.isBlank(customerAddressSDO.getOrgSaleOrganizationCode()) ||
//                StringUtils.isBlank(customerAddressSDO.getChannelCode()) ||
//                StringUtils.isBlank(customerAddressSDO.getItemGroup())) {
//            log.error("此客户的客户编码、地址编码、销售组织、货品组、业务渠道字段存在空值，地址名称：{}", customerAddressSDO.getAddressName());
//            return false;
//        }
//        //根据唯一键(客户编码、渠道、货品组、销售组织)查询平台的唯一的客户地址数据，存在就更新 不存在就新增
//        CustomerAddressLoadListRequest customerAddressLoadListRequest = new CustomerAddressLoadListRequest();
//        customerAddressLoadListRequest.setCustomerCode(customerAddressSDO.getCustomerCode());
//        customerAddressLoadListRequest.setAddressCode(customerAddressSDO.getAddressCode());
//        customerAddressLoadListRequest.setOrgSaleOrganizationCode(customerAddressSDO.getOrgSaleOrganizationCode());
////        customerAddressLoadListRequest.setOrgSaleChannelCode(customerAddressSDO.getOrgSaleChannelCode());
////        customerAddressLoadListRequest.setOrgSaleDepartmentCode(customerAddressSDO.getOrgSaleDepartmentCode());
//        customerAddressLoadListRequest.setChannelCode(customerAddressSDO.getChannelCode());
//        customerAddressLoadListRequest.setItemGroup(customerAddressSDO.getItemGroup());
//        customerAddressLoadListRequest.setType(1);
//        Result<List<CustomerAddress>> addressListResult = customerAddressService.loadCustomerAddressList(customerAddressLoadListRequest);
//        if (CollectionUtils.isEmpty(addressListResult.getResult())) {
//            CustomerAddress customerAddress = new CustomerAddress();
//            BeanUtils.copyProperties(customerAddressSDO, customerAddress);
//            customerAddress.setFeatures(customerAddressSDO.getFeatures());
//            customerAddress.setGmtCreate(new Date());
//            customerAddress.setGmtModified(new Date());
//            customerAddress.setFeatures(customerAddressSDO.getFeatures());
//            CreateCustomerAddressResponse addressResponse = customerAddressService.createCustomerAddress(customerAddress);
//            return StringUtils.isNotEmpty(addressResponse.getLastInsertId());
//        } else {
//            CustomerAddress origin = addressListResult.getResult().stream().findFirst().get();
//            CustomerAddress updateRequest = new CustomerAddress();
//            BeanUtils.copyProperties(customerAddressSDO, updateRequest);
//            updateRequest.setId(origin.getId());
//            updateRequest.setGmtModified(new Date());
//            updateRequest.setPrincipal(null);
//            updateRequest.setFeatures(customerAddressSDO.getFeatures());
//            UpdateCustomerAddressResponse updateCustomerAddressResponse = customerAddressService.updateCustomerAddress(updateRequest);
//            return updateCustomerAddressResponse.getCount() == 1;
//        }
//    }
//
//    public void createOrUpdateCustomer(CustomerSDO customerSDO, CustomerSaleScopeSDO customerSaleScopeSDO, CustomerAddressSDO customerAddressSDO) {
//        if (!this.saveOrUpdateCustomerMainData(customerSDO)) {
//            //失败就重试一次
////            if (!this.saveOrUpdateCustomerMainData(customerSDO)) {
////            }
//            throw new FacadeException(ErrorMessage.code("OTS-01-004-02-16-005"));
//        }
//        if (!this.saveOrUpdateCustomerSaleScope(customerSaleScopeSDO)) {
//            //失败就重试一次
//            if (!this.saveOrUpdateCustomerSaleScope(customerSaleScopeSDO)) {
//                throw new FacadeException(ErrorMessage.code("OTS-01-004-02-16-006"));
//            }
//        }
//        if (!this.saveOrUpdateCustomerAddress(customerAddressSDO)) {
//            //失败就重试一次
//            if (!this.saveOrUpdateCustomerAddress(customerAddressSDO)) {
//                throw new FacadeException(ErrorMessage.code("OTS-01-004-02-16-007"));
//            }
//        }
//    }
//
//    public List<Customer> batchQueryCustomerMainData(List<String> customerCodes) {
//        List<Customer> resultList = Lists.newArrayList();
//        BatchQueryRequest queryRequest = BatchQueryRequest.builder().codes(customerCodes).statusList(Lists.newArrayList(1, 0, -1)).build();
//        BatchQueryResponse batchQueryResponse = customerService.batchQuery(queryRequest);
//        if (Objects.isNull(batchQueryResponse) || CollectionUtils.isEmpty(batchQueryResponse.getResult())) {
//            return Lists.newArrayList();
//        }
//        resultList.addAll(batchQueryResponse.getResult());
//        int pages = getTotalPages(batchQueryResponse.getTotal());
//        if (pages >= 2) {
//            IntStream.rangeClosed(2, pages).forEach(i -> {
//                queryRequest.setStart((i - 1) * LIMIT);
//                BatchQueryResponse currentResult = customerService.batchQuery(queryRequest);
//                if (Objects.nonNull(currentResult) && CollectionUtils.isNotEmpty(currentResult.getResult())) {
//                    resultList.addAll(currentResult.getResult());
//                }
//            });
//        }
//        return resultList;
//    }
//
//    public List<CustomerAddressSDO> batchQueryCustomerAddress(List<CustomerAddressSDO> addressSDOS) {
//        List<CustomerAddress> resultList = Lists.newArrayList();
//        Set<String> addressCodes = addressSDOS.stream().map(CustomerAddressSDO::getAddressCode).collect(Collectors.toSet());
//        Set<String> customerCodes = addressSDOS.stream().map(CustomerAddressSDO::getCustomerCode).collect(Collectors.toSet());
//        Set<String> orgSaleOrgs = addressSDOS.stream().map(CustomerAddressSDO::getOrgSaleOrganizationCode).collect(Collectors.toSet());
//        Set<String> channelCodes = addressSDOS.stream().map(CustomerAddressSDO::getChannelCode).collect(Collectors.toSet());
//        Set<String> itemGroups = addressSDOS.stream().map(CustomerAddressSDO::getItemGroup).collect(Collectors.toSet());
//        BatchQueryAddressByConditionRequest batchQueryRequest =
//                BatchQueryAddressByConditionRequest.builder()
//                        .addressCodes(Lists.newArrayList(addressCodes))
//                        .customerCodes(Lists.newArrayList(customerCodes))
//                        .orgSalesOrganizationCodes(Lists.newArrayList(orgSaleOrgs))
//                        .channelCodes(Lists.newArrayList(channelCodes))
//                        .itemGroups(Lists.newArrayList(itemGroups))
//                        .statusList(Lists.newArrayList(1, 0, -1))
//                        .limit(LIMIT)
//                        .build();
//        Result<List<CustomerAddress>> batchQueryResponse = customerAddressService.batchQueryAddressByCondition(batchQueryRequest);
//        if (Objects.isNull(batchQueryResponse) || CollectionUtils.isEmpty(batchQueryResponse.getResult())) {
//            return Lists.newArrayList();
//        }
//        resultList.addAll(batchQueryResponse.getResult());
//        int pages = getTotalPages(batchQueryResponse.getTotal());
//        if (pages >= 2) {
//            IntStream.rangeClosed(2, pages).forEach(i -> {
//                batchQueryRequest.setStart((i - 1) * LIMIT);
//                Result<List<CustomerAddress>> currentResult = customerAddressService.batchQueryAddressByCondition(batchQueryRequest);
//                if (Objects.nonNull(currentResult) && CollectionUtils.isNotEmpty(currentResult.getResult())) {
//                    resultList.addAll(currentResult.getResult());
//                }
//            });
//        }
//        return resultList.stream().map(it -> {
//            CustomerAddressSDO addressSDO = new CustomerAddressSDO();
//            BeanUtils.copyProperties(it, addressSDO);
//            addressSDO.setId(String.valueOf(it.getId()));
//            return addressSDO;
//        }).collect(Collectors.toList());
//    }
//
//    public List<CustomerSaleScopeSDO> batchQueryCustomerScopes(List<CustomerSaleScopeSDO> customerSaleScopeSDOs) {
//        List<CustomerSaleScope> resultList = Lists.newArrayList();
//        Set<String> customerCodes = customerSaleScopeSDOs.stream().map(CustomerSaleScopeSDO::getCustomerCode).collect(Collectors.toSet());
//        Set<String> orgSaleOrgs = customerSaleScopeSDOs.stream().map(CustomerSaleScopeSDO::getOrgSaleOrganizationCode).collect(Collectors.toSet());
//        Set<String> channelCodes = customerSaleScopeSDOs.stream().map(CustomerSaleScopeSDO::getChannelCode).collect(Collectors.toSet());
//        Set<String> itemGroups = customerSaleScopeSDOs.stream().map(CustomerSaleScopeSDO::getItemGroup).collect(Collectors.toSet());
//        BatchCustomerScopesByConditonRequest conditionRequest = BatchCustomerScopesByConditonRequest.builder()
//                .customerCodes(Lists.newArrayList(customerCodes))
//                .orgSalesOrganizationCodes(Lists.newArrayList(orgSaleOrgs))
//                .channelCodes(Lists.newArrayList(channelCodes))
//                .itemGroups(Lists.newArrayList(itemGroups))
//                .statusList(Lists.newArrayList(1, 0, -1))
//                .limit(LIMIT)
//                .build();
//        Result<List<CustomerSaleScope>> listResult = customerSaleScopeService.batchCustomerScopesByConditon(conditionRequest);
//        if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
//            return Lists.newArrayList();
//        }
//        resultList.addAll(listResult.getResult());
//        int pages = getTotalPages(listResult.getTotal());
//        if (pages >= 2) {
//            IntStream.rangeClosed(2, pages).forEach(i -> {
//                conditionRequest.setStart((i - 1) * LIMIT);
//                Result<List<CustomerSaleScope>> currentResult = customerSaleScopeService.batchCustomerScopesByConditon(conditionRequest);
//                if (Objects.nonNull(currentResult) && CollectionUtils.isNotEmpty(currentResult.getResult())) {
//                    resultList.addAll(currentResult.getResult());
//                }
//            });
//        }
//        return resultList.stream().map(it -> {
//            CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
//            BeanUtils.copyProperties(it, saleScopeSDO);
//            saleScopeSDO.setId(String.valueOf(it.getId()));
//            return saleScopeSDO;
//        }).collect(Collectors.toList());
//    }
//
//    private int getTotalPages(int total) {
//        if (total % LIMIT == 0) {
//            return total / LIMIT;
//        } else {
//            return (total / LIMIT) + 1;
//        }
//    }
//
//    public Boolean batchCreateCustomers(List<CustomerSDO> notExistCustomers) {
//        if (CollectionUtils.isEmpty(notExistCustomers)) {
//            return true;
//        }
//        List<Customer> saveRequestList = notExistCustomers.stream().map(it -> {
//            Customer customer = new Customer();
//            BeanUtils.copyProperties(it, customer);
//            customer.setStatus(String.valueOf(it.getStatus()));
//            return customer;
//        }).collect(Collectors.toList());
//        BatchSaveCustomersRequest customersRequest = BatchSaveCustomersRequest.builder().customers(saveRequestList).build();
//        BatchSaveCustomersResponse batchSaveCustomersResponse = customerService.batchSaveCustomers(customersRequest);
//        log.info("新增客户档案数量：{}", batchSaveCustomersResponse.getCount());
//        return saveRequestList.size() == batchSaveCustomersResponse.getCount();
//    }
//
//    public Boolean batchUpdateCustomers(List<Customer> existCustomers, Map<String, CustomerSDO> updateMap) {
//        if (CollectionUtils.isEmpty(existCustomers)) {
//            return true;
//        }
//        int count = 0;
//        for (Customer existCustomer : existCustomers) {
//            Customer updateRequest = new Customer();
//            CustomerSDO targetSDO = updateMap.get(existCustomer.getCode());
//            BeanUtils.copyProperties(targetSDO, updateRequest);
//            updateRequest.setId(existCustomer.getId());
//            updateRequest.setGmtModified(new Date());
//            UpdateCustomerResponse updateCustomerResponse = customerService.updateCustomer(updateRequest);
//            count = count + updateCustomerResponse.getCount();
//        }
//        log.info("更新客户档案数量：{}", count);
//        return existCustomers.size() == count;
//    }
//
//    public Boolean batchCreateCustomerScopes(List<CustomerSaleScopeSDO> notExistScopes) {
//        if (CollectionUtils.isEmpty(notExistScopes)) {
//            return true;
//        }
//        List<CustomerSaleScope> saleScopes = notExistScopes.stream().map(it -> {
//            CustomerSaleScope customerSaleScope = new CustomerSaleScope();
//            BeanUtils.copyProperties(it, customerSaleScope);
//            return customerSaleScope;
//        }).collect(Collectors.toList());
//        BatchSaveCustomerScopesRequest customerScopesRequest = BatchSaveCustomerScopesRequest.builder().customerScopes(saleScopes).build();
//        BatchSaveCustomerScopesResponse scopesResponse = customerSaleScopeService.batchSaveCustomerScopes(customerScopesRequest);
//        log.info("新增客户售达方数量：{}", scopesResponse.getCount());
//        return scopesResponse.getCount() == notExistScopes.size();
//    }
//
//    public Boolean batchUpdateCustomerScopes(List<CustomerSaleScopeSDO> existScopeList, Map<String, CustomerSaleScopeSDO> updateMap) {
//        if (CollectionUtils.isEmpty(existScopeList)) {
//            return true;
//        }
//        int count = 0;
//        for (CustomerSaleScopeSDO existScope : existScopeList) {
//            CustomerSaleScope updateRequest = new CustomerSaleScope();
//            CustomerSaleScopeSDO targetSDO = updateMap.get(getScopeCombineKey(existScope));
//            if (Objects.nonNull(targetSDO)) {
//                BeanUtils.copyProperties(targetSDO, updateRequest);
//                updateRequest.setId(Long.valueOf(existScope.getId()));
//                updateRequest.setGmtModified(new Date());
//                refreshCustomerSaleScope(existScope, updateRequest);
//                UpdateCustomerSaleScopeResponse customerSaleScopeResponse = customerSaleScopeService.updateCustomerSaleScope(updateRequest);
//                count = count + customerSaleScopeResponse.getCount();
//            }
//        }
//        log.info("更新客户售达方数量：{}", count);
//        return existScopeList.size() == count;
//    }
//
//    public String getScopeCombineKey(CustomerSaleScopeSDO scope) {
//        return scope.getCustomerCode() + scope.getOrgSaleOrganizationCode() + scope.getChannelCode() + scope.getItemGroup();
//    }
//
//    public String getAddressCombineKey(CustomerAddressSDO address) {
//        return address.getCustomerCode() + address.getAddressCode() + address.getOrgSaleOrganizationCode() + address.getChannelCode() + address.getItemGroup();
//    }
//
//    public Boolean batchCreateCustomerAddresses(List<CustomerAddressSDO> notExistAddresses) {
//        if (CollectionUtils.isEmpty(notExistAddresses)) {
//            return true;
//        }
//        List<CustomerAddress> addresses = notExistAddresses.stream().map(it -> {
//            CustomerAddress customerAddress = new CustomerAddress();
//            BeanUtils.copyProperties(it, customerAddress);
//            return customerAddress;
//        }).collect(Collectors.toList());
//        BatchSaveCustomerAddressesRequest addressesRequest = BatchSaveCustomerAddressesRequest.builder().customerAddresses(addresses).build();
//        BatchSaveCustomerAddressesResponse batchSaveCustomerAddressesResponse = customerAddressService.batchSaveCustomerAddresses(addressesRequest);
//        return batchSaveCustomerAddressesResponse.getCount() == notExistAddresses.size();
//    }
//
//    public Boolean batchUpdateCustomerAddresses(List<CustomerAddressSDO> existAddressList, Map<String, CustomerAddressSDO> addressUpdatedMap) {
//        if (CollectionUtils.isEmpty(existAddressList)) {
//            return true;
//        }
//
//        int count = 0;
//        for (CustomerAddressSDO addressSDO : existAddressList) {
//            CustomerAddress updateRequest = new CustomerAddress();
//            CustomerAddressSDO targetSDO = addressUpdatedMap.get(getAddressCombineKey(addressSDO));
//            if (Objects.nonNull(targetSDO)) {
//                BeanUtils.copyProperties(targetSDO, updateRequest);
//                updateRequest.setId(Long.valueOf(addressSDO.getId()));
//                updateRequest.setGmtModified(new Date());
//                refreshCustomerAddress(addressSDO, updateRequest);
//                UpdateCustomerAddressResponse updateCustomerAddressResponse = customerAddressService.updateCustomerAddress(updateRequest);
//                count = count + updateCustomerAddressResponse.getCount();
//            }
//        }
//        return existAddressList.size() == count;
//    }
//
//    /**
//     * 更新字段赋值
//     *
//     * @param source
//     * @param target
//     */
//    private void refreshCustomerSaleScope(CustomerSaleScopeSDO source, CustomerSaleScope target) {
//        // 如果有指派负责人，则不需要变更 销售渠道等字段
//        if (StringUtils.isNotBlank(source.getPrincipal())) {
//            target.setOrgSaleChannelCode(null);
//            target.setOrgSaleDepartmentCode(null);
//        }
//    }
//
//    /**
//     * 更新字段赋值
//     *
//     * @param source
//     * @param target
//     */
//    private void refreshCustomerAddress(CustomerAddressSDO source, CustomerAddress target) {
//        // 如果有指派负责人，则不需要变更 销售渠道等字段
//        if (StringUtils.isNotBlank(source.getPrincipal())) {
//            target.setOrgSaleChannelCode(null);
//            target.setOrgSaleDepartmentCode(null);
//        }
//    }
//}
